package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 统计营业额
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverReport(LocalDate begin, LocalDate end) {
        //遍历取出日期范围
        List<LocalDate> localDateList = new ArrayList<>();
        while (!begin.equals(end)) {
            localDateList.add(begin);
            begin = begin.plusDays(1);
        }
        localDateList.add(end);
        List<Double> turnoverList = new ArrayList<>();
        //遍历日期，查出每天的订单营业额
        for (LocalDate date : localDateList) {
            LocalDateTime start = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime ends = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("start", start);
            map.put("end", ends);
            map.put("status", Orders.COMPLETED);
            Double turnover = ordersMapper.getByStatusAndTime(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }

        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .dateList(StringUtils.join(localDateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
        return turnoverReportVO;
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userReport(LocalDate begin, LocalDate end) {
        //遍历取出日期范围
        List<LocalDate> localDateList = new ArrayList<>();
        while (!begin.equals(end)) {
            localDateList.add(begin);
            begin = begin.plusDays(1);
        }
        localDateList.add(end);
        List<Integer> userTotal = new ArrayList<>();        //用户总量
        List<Integer> newUserNumber = new ArrayList<>();        //新用户数量
        //日期范围区间内查询每一天的数据
        for (LocalDate date : localDateList) {
            LocalDateTime start = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime ends = LocalDateTime.of(date, LocalTime.MAX);
            Map<Object, Object> map = new HashMap<>();
            map.put("start", start);
            map.put("end", ends);
            Integer sum = userMapper.getTotalNumber(ends);
            userTotal.add(sum);
            Integer newUser = userMapper.getNewUserNumber(map);
            newUserNumber.add(newUser);
        }
        return UserReportVO.builder()
                .totalUserList(StringUtils.join(userTotal, ","))
                .newUserList(StringUtils.join(newUserNumber, ","))
                .dateList(StringUtils.join(localDateList, ","))
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersReport(LocalDate begin, LocalDate end) {
        //遍历取出日期范围
        List<LocalDate> localDateList = new ArrayList<>();
        while (!begin.equals(end)) {
            localDateList.add(begin);
            begin = begin.plusDays(1);
        }
        localDateList.add(end);
        //统计每一天的订单数量和有效订单数
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : localDateList) {
            LocalDateTime start = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime ends = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("start", start);
            map.put("end", ends);
            //查询当天的订单
            Integer todayOrder = ordersMapper.selectTodayOrders(map);
            orderCountList.add(todayOrder);
            //查询当天的有效订单
            map.put("status", Orders.COMPLETED);
            Integer validOrder = ordersMapper.selectTodayValidOrders(map);
            validOrderCountList.add(validOrder);
        }
        //统计订单总数和有效订单总数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(localDateList, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 销量top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10Report(LocalDate begin, LocalDate end) {
        LocalDateTime beginDate = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endDate = LocalDateTime.of(end, LocalTime.MAX);
        Map map = new HashMap();
        map.put("start", beginDate);
        map.put("end", endDate);
        map.put("status", Orders.COMPLETED);
        List<GoodsSalesDTO> salesTop10 = ordersMapper.getSalesTop10(map);
        List<String> nameList = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * 数据导出
     */
    @Override
    public void export(HttpServletResponse response){
        //1. 查询数据库，获取营业数据，查询最近30天的营业数据
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MIN));
        //2. 通过poi将数据写入到excel文件中
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            //基于模板文件创建excel文件
            XSSFWorkbook excel = new XSSFWorkbook(is);
            //获取表格sheet
            XSSFSheet sheet = excel.getSheetAt(0);
            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + begin + "-" + end);
            //填充各种营业数据
            //获取第四行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());        //营业额
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate()); //订单完成率
            row.getCell(6).setCellValue(businessData.getNewUsers());        //新增用户数
            //获取第五行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());     //有效订单数
            row.getCell(4).setCellValue(businessData.getUnitPrice());       //平均客单价

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDataVO.getTurnover());
                row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO.getNewUsers());
            }
            //3.  通过输出流将excel文件下载到客户端浏览器
            ServletOutputStream os = response.getOutputStream();
            excel.write(os);

            //关闭资源
            os.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        try {
            is.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
